package com.example.sunmiv1.utils.net;

import android.content.Context;
import android.util.Log;
import android.widget.Toast;

import com.example.sunmiv1.utils.LogUtil;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;

import okhttp3.Call;
import okhttp3.FormBody;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

/**
 * Created by Administrator on 2016/8/17.
 */
public class HttpUtils {

    static OkHttpClient sClient = null;
    private static final String TAG = "HttpUtils";

    public synchronized static OkHttpClient getClient() {
        if (sClient == null) {
            sClient = new OkHttpClient.Builder()
                    .connectTimeout(600000, TimeUnit.SECONDS)
                    .readTimeout(600000, TimeUnit.SECONDS)
                    .build();
        }

        return sClient;
    }

    public static void postSync(String str) {
//        private static final String ENDPOINT = "https://api.github.com/repos/square/okhttp/contributors";
        OkHttpClient client = new OkHttpClient.Builder().build();
        Request request = new Request.Builder()
                .url(str)
                .build();
        try {
            Response response = client.newCall(request).execute();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void get(Context context, String url, HashMap<String, String> params, TextCallBack callBack) {
        OkHttpClient client = getClient();
        Set<Map.Entry<String, String>> set = params.entrySet();

        boolean isFirst = true;
        for (Map.Entry<String, String> entry : set) {
            if (isFirst) {
                url += "?";
                isFirst = false;
            } else {
                url += "&";
            }
            url += entry.getKey() + "=" + entry.getValue();
        }
        Request request = new Request.Builder().url(url).get().build();
        client.newCall(request).enqueue(callBack);
    }

    public static void post(Context context, String url, HashMap<String, String> params, TextCallBack callBack) {
        OkHttpClient client = getClient();
        FormBody.Builder builder = new FormBody.Builder();
        Set<Map.Entry<String, String>> set = params.entrySet();
        for (Map.Entry<String, String> entry : set) {
            builder.add(entry.getKey(), entry.getValue());
        }
        Request request = new Request.Builder().url(url).post(builder.build())
                .build();
        client.newCall(request).enqueue(callBack);
    }

    /**
     * @param context
     * @param url        接口
     * @param jsonObject json對象
     * @param callBack
     */
    public static void post(Context context, String url, JSONObject jsonObject, TextCallBack callBack) {
        System.out.println(url);
        OkHttpClient client = getClient();
        FormBody.Builder builder = new FormBody.Builder();
        Iterator<String> keys = jsonObject.keys();
        while (keys.hasNext()) {
            String key = String.valueOf(keys.next());
            try {
                String value = jsonObject.get(key).toString();
                builder.add(key, value);
            } catch (JSONException e) {
                e.printStackTrace();
            }

        }
        Request request = new Request.Builder().url(url).post(builder.build()).build();
        LogUtil.e("接口鏈接", "==========" + url);
        LogUtil.e("傳送數據", "==========" + jsonObject);
//        Call call = client.newCall(request);

        client.newCall(request).enqueue(callBack);
    }




    public static void postSync(Context context, String url, JSONObject jsonObject) {
        OkHttpClient client = getClient();
        Log.e("gouwuche", url + jsonObject);
        FormBody.Builder builder = new FormBody.Builder();
        Iterator<String> keys = jsonObject.keys();
        while (keys.hasNext()) {
            String key = String.valueOf(keys.next());
            try {
                String value = jsonObject.get(key).toString();
                builder.add(key, value);
            } catch (JSONException e) {
                e.printStackTrace();
            }

        }
        Request request = new Request.Builder().url(url).post(builder.build()).build();
        try {
            client.newCall(request).execute();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void postVideo(Context context, String url, JSONObject jsonObject, TextCallBack callBack) {
        OkHttpClient client = getClient();

        FormBody.Builder builder = new FormBody.Builder();
        Iterator<String> keys = jsonObject.keys();
        while (keys.hasNext()) {
            String key = String.valueOf(keys.next());
            try {
                String value = jsonObject.get(key).toString();
                byte[] bytes = string2bytes(value);
                String byte2String = new String(bytes);
                builder.add(key, byte2String);
            } catch (JSONException e) {
                e.printStackTrace();
            }

        }
        Request request = new Request.Builder().url(url)
                .post(builder.build())
                .build();

        client.newCall(request).enqueue(callBack);
    }

    private static byte[] string2bytes(String filePath) {
        if (new File(filePath).exists() && new File(filePath).isFile()) {
            FileInputStream fileInputStream = null;
            byte[] bytes;
            try {
                fileInputStream = new FileInputStream(new File(filePath));
                bytes = new byte[1024];
                int read = 0;
                while ((read = fileInputStream.read()) != -1) {
                    fileInputStream.read(bytes, 0, read);
                }
                return bytes;
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                try {
                    fileInputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        } else {
            Log.e(TAG, "string2bytes: 文件不存在=========");
        }
        return null;
    }

    public static void postAndFile(Context context, String url, JSONObject jsonObject, File file, TextCallBack callBack) {
        ACache aCache = ACache.get(context);
        if ("0".equals(aCache.getAsString("is_wifi"))) {
            Toast.makeText(context, "沒有網絡,請連接網絡後重試", Toast.LENGTH_SHORT).show();
            return;
        }

        MultipartBody.Builder requestBody = new MultipartBody.Builder().setType(MultipartBody.FORM);
        if (file != null) {
            // MediaType.parse() 裏面是上傳的文件類型。
            RequestBody body = RequestBody.create(MediaType.parse("image/*"), file);
            // 參數分別爲， 請求key ，文件名稱 ， RequestBody
            requestBody.addFormDataPart("file", file.getName(), body);
        }
        OkHttpClient client = getClient();
        Iterator<String> keys = jsonObject.keys();
        while (keys.hasNext()) {
            String key = String.valueOf(keys.next());
            try {
                String value = jsonObject.get(key).toString();
//                builder.add(key, value);
                requestBody.addFormDataPart(key, value);
            } catch (JSONException e) {
                e.printStackTrace();
            }

        }

        Request request = new Request.Builder().url(url).post(requestBody.build()).build();
//        eLength("接口鏈接", "==========" + url);
//        eLength("傳送數據", "==========" + jsonObject);
        client.newCall(request).enqueue(callBack);

    }

    public static void postAndFile(Context context, String url, JSONObject jsonObject, File file, int paramInt, TextCallBack callBack) {
        ACache aCache = ACache.get(context);
        if ("0".equals(aCache.getAsString("is_wifi"))) {
            Toast.makeText(context, "沒有網絡,請連接網絡後重試", Toast.LENGTH_SHORT).show();
            return;
        }

        MultipartBody.Builder requestBody = new MultipartBody.Builder().setType(MultipartBody.FORM);
        if (file != null) {
            // MediaType.parse() 裏面是上傳的文件類型。
//            RequestBody body = RequestBody.create(MediaType.parse("image/*"), file);
//            // 參數分別爲， 請求key ，文件名稱 ， RequestBody
//            requestBody.addFormDataPart("file", file.getName(), body);
            if (paramInt == 1) {
                RequestBody requestBody1 = RequestBody.create(MediaType.parse("image/*"), file);
                requestBody.addFormDataPart("file", file.getName(), requestBody1);
            } else if (paramInt == 2) {
                RequestBody requestBody2 = RequestBody.create(MediaType.parse("video/*"), file);
                requestBody.addFormDataPart("file", file.getName(), requestBody2);
            }
        }
        OkHttpClient client = getClient();
        Iterator<String> keys = jsonObject.keys();
        while (keys.hasNext()) {
            String key = String.valueOf(keys.next());
            try {
                String value = jsonObject.get(key).toString();
//                builder.add(key, value);
                requestBody.addFormDataPart(key, value);
            } catch (JSONException e) {
                e.printStackTrace();
            }

        }

        Request request = new Request.Builder().url(url).post(requestBody.build()).build();
        Log.d("接口鏈接", "==========" + url);
        Log.d("傳送數據", "==========" + jsonObject);
        client.newCall(request).enqueue(callBack);

    }

}
